from flask import request, make_response
import redis
import time

from utils import utils


class UserPay:
    @staticmethod
    def get_balance():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "balance": "Unknown"
        }

        data = request.get_json()
        user_id = data["id"]

        balance = db.hget(user_id, "balance")
        res["balance"] = float(balance)

        return make_response(res)

    @staticmethod
    def inc_balance():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "ok": True
        }

        data = request.get_json()
        user_id = data["id"]
        inc = data["inc"]

        balance = db.hget(user_id, "balance")
        balance = float(balance) + inc
        db.hset(user_id, "balance", balance)
        return make_response(res)

    @staticmethod
    def pay_order():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "ok": True
        }

        data = request.get_json()
        user_id = data["id"]

        balance = db.hget(user_id, "balance")
        order_id = db.hget(user_id, "order")
        where = db.hget(user_id, "where")
        cost = db.hget(order_id, "cost")
        is_payed = db.hget(order_id, "is_payed")

        if where != "exit" or is_payed == "yes" or balance < cost:
            res["ok"] = False
        else:
            balance -= cost
            db.hset(user_id, "balance", balance)
            db.hset(order_id, "is_payed", "yes")
        return make_response(res)

    @staticmethod
    def get_order():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "order_id": ""
        }

        data = request.get_json()
        user_id = data["id"]

        order_id = db.hget(user_id, "order")
        res["order_id"] = order_id
        res["charge_time"] = float(db.hget(order_id, "charge_time"))

        generate_time_stamp = float(db.hget(order_id, "generate_time"))
        start_time_stamp = float(db.hget(order_id, "start_time"))
        end_time_stamp = float(db.hget(order_id, "end_time"))
        res["generate_time"] = time.strftime("%Y-%m-%d %H:%M", time.localtime(generate_time_stamp))
        res["start_time"] = time.strftime("%Y-%m-%d %H:%M", time.localtime(start_time_stamp))
        res["end_time"] = time.strftime("%Y-%m-%d %H:%M", time.localtime(end_time_stamp))

        res["charge_cost"] = db.hget(order_id, "charge_cost")
        res["service_cost"] = db.hget(order_id, "service_cost")
        res["cost"] = db.hget(order_id, "cost")

        return make_response(res)




